import React, { useState, useEffect } from 'react';
import { Progress, Typography } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';

const { Paragraph } = Typography;

const TimerProgress = ({ waitingTime, interval, content }) => {
  // 无论 interval 是否为0，都先调用 Hooks
  const [progress, setProgress] = useState(0);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    // 如果 interval 为0，则不启动计时器
    if (interval === 0) return;

    // 计算总步数（取整数）
    const totalSteps = Math.floor(waitingTime / interval);
    let count = 0;

    const timer = setInterval(() => {
      setElapsedTime(prev => prev + interval);

      if (count >= totalSteps) {
        setProgress(99);
        clearInterval(timer);
      } else {
        // 平均每步应增加的值
        const avgIncrement = 99 / totalSteps;
        // 随机因子在 0.5 到 1.5 之间
        const randomFactor = Math.random() + 0.5;
        const increment = avgIncrement * randomFactor;

        setProgress(prev => {
          let newProgress = prev + increment;
          if (newProgress > 99) {
            newProgress = 99;
          }
          return parseFloat(newProgress.toFixed(2));
        });
        count++;
      }
    }, interval * 1000);

    return () => clearInterval(timer);
  }, [waitingTime, interval]);

  // 渲染阶段根据 interval 判断输出
  if (interval === 0) {
    return (
      <div style={{ width: '100%' }}>
        <Paragraph
          ellipsis={{
            rows: 1,
            copyable: false,
            expandable: 'collapsible',
            expanded,
            onExpand: (_, info) => setExpanded(info.expanded),
          }}
        >
          {content}
        </Paragraph>

        <Progress percent={100} />
      </div>
    );
  }

  return (
    <div style={{ width: '100%' }}>
      <p>
        {content}
      </p>
      <p>
        <span style={{ marginBottom: '8px' }}>takes：{elapsedTime} seconds</span>
        <span>
          <Progress percent={progress} />
        </span>
      </p>
    </div>
  );
};

export default TimerProgress;
